package dao;

import entity.Movie;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;
import javax.persistence.*;

/**
 *
 * @author Javier
 */
public class MovieDao {
    private EntityManagerFactory emf = null;
    private EntityManager em = null;
    private EntityTransaction et = null;
    
    public boolean persistMovie(Movie movie){
        boolean result = false;
        
        try{
            emf = Persistence.createEntityManagerFactory("GRLUPUPU");
            em = emf.createEntityManager();
            et = em.getTransaction();
            et.begin();
            movie = em.merge(movie);
            em.flush();
            em.persist(movie);
            et.commit();
            result = true;
        }catch(Exception e){
            if (em != null && et != null){
                et.rollback();
            }
        }finally{
            if (em != null){
                em.clear();
                em.close();
            }
            return result;
        }
    }
    
    public List<Movie> findMovieByName(String wordsToLookFor){
        //Returned value
        List<Movie> movies = new ArrayList();
        // Set which contains the movie's id only once
        HashSet<Integer> moviesId = new HashSet();
        
        //Divide the string into its tokens.
        //String wordsToLookFor = "palabras para la busqueda de peliculas";
        StringTokenizer tokens=new StringTokenizer(wordsToLookFor, " ");
        ArrayList<String> words = new ArrayList();
        int j = 0;
        while (tokens.hasMoreTokens()){
            String next=tokens.nextToken();
            words.add(next);
            //System.out.println(words.get(j).toString());
            j++;
        }
        
        for( int i = 0; i < words.size(); i++){
            // List of movies in each iteration.
            List<Movie> m;
        
            try{
                    emf = Persistence.createEntityManagerFactory("GRLUPUPU");
                    em = emf.createEntityManager();
                    et = em.getTransaction();
                    et.begin();

                    String qlString = "SELECT m FROM Movie AS m WHERE m.movName LIKE :code"; 
                    Query q = em.createQuery(qlString, Movie.class);
                    q.setParameter("code", "%"+words.get(i).toString()+"%");
                    m = q.getResultList();
                    //Adding the Id's only once
                    for ( int k = 0; k < m.size(); k++){
                        moviesId.add(new Integer (m.get(k).getIdMovie()));
                    }

                    et.commit();    
                }catch(Exception e){
                    if (em != null && et != null){
                        et.rollback();
                    }
                }finally{
                    if (em != null){
                        em.clear();
                        em.close();
                     }   
                }
                    Object[] result = moviesId.toArray();
                    for (int l = 0; l < moviesId.size(); l++){
                        movies.add((Movie)findMovieById((Integer)result[l]));
                    }
        }
        return movies;
    }
    
    
    
     public Movie findMovieById (Integer id){
            Movie movie = null;
            try{
                emf = Persistence.createEntityManagerFactory("GRLUPUPU");
                em = emf.createEntityManager();
                et = em.getTransaction();
                et.begin();

                Query q = em.createNamedQuery("Movie.findByIdMovie", Movie.class);
                q.setParameter("idMovie", id);
                movie = (Movie) q.getSingleResult();
                et.commit();

            }catch(Exception e){
                if (em != null && et != null){
                    et.rollback();
                }
            }finally{
                if (em != null){
                    em.clear();
                    em.close();
                }

            }     
            return movie;
    }

    public List<Movie> findMoviesByGenre (String genre){
        List<Movie> movies = null;
        try{
            emf = Persistence.createEntityManagerFactory("GRLUPUPU");
            em = emf.createEntityManager();
            et = em.getTransaction();
            et.begin();
            
            Query q = em.createNamedQuery("Movie.findByGenre", Movie.class);
            q.setParameter("movGenre", genre);
            movies = q.getResultList();
            et.commit();

        }catch(Exception e){
            if (em != null && et != null){
                et.rollback();
            }
        }finally{
            if (em != null){
                em.clear();
                em.close();
            }
            
        }     
        return movies;
    }
     
    public boolean deleteMovie(Movie movie) {
        boolean result = false;
        try {
            emf = Persistence.createEntityManagerFactory("GRLUPUPU");
            em = emf.createEntityManager();
            et = em.getTransaction();
            et.begin();        
            em.remove(movie);
            em.getTransaction().commit();
            result = true;
        } catch (Exception e) {
            if (em != null && et != null){
                et.rollback();
            }
        } finally {
            if (em != null){
                em.clear();
                em.close();
            }
            return result;
        }
    }
}
